package com.example.petstore_2.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.example.petstore_2.common.CommonResponse;
import com.example.petstore_2.domain.*;
import com.example.petstore_2.service.*;
import com.example.petstore_2.util.JWTUtil;
import com.example.petstore_2.util.ZFBqrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private LineItemService lineItemService;

    /**
     * 获取全部订单
     * @param token
     * @return
     */
    @GetMapping("/orders")
    public CommonResponse userGetAllOrder(@RequestHeader("Authorization") String token){
        String username = JWTUtil.getTokenInfo(token, "username");
//        System.out.println(username);
        return orderService.userFindAllOrder(username);
    }

    /**
     * 获取未收发货的订单
     * @param token
     * @return
     */
    @GetMapping("/noShipOrders")
    public CommonResponse userFindNoShipOrder(@RequestHeader("Authorization") String token){
        String username = JWTUtil.getTokenInfo(token, "username");
        return orderService.userFindNoShipOrder(username);
    }

    /**
     * 获取已发货的订单
     * @param token
     * @return
     */
    @GetMapping("/shipOrders")
    public CommonResponse<List<Order>> userFindShipOrder(@RequestHeader("Authorization") String token){
        String username = JWTUtil.getTokenInfo(token, "username");
        return orderService.userFindShipOrder(username);
    }

    /**
     * 获取未付款的订单
     * @param token
     * @return
     */
    @GetMapping("/noPayOrders")
    public CommonResponse<List<Order>> userFindNoPayOrder(@RequestHeader("Authorization") String token){
        String username = JWTUtil.getTokenInfo(token, "username");
        return orderService.userFindNoPayOrder(username);
    }

    /**
     * 获取用户未收到货的订单
     * @param token
     * @return
     */
    @GetMapping("/noGetOrders")
    @ResponseBody
    public CommonResponse findNoGetOrder(@RequestHeader("Authorization") String token){
        String username = JWTUtil.getTokenInfo(token, "username");
        return orderService.userFindNoGetOrder(username);
    }

    /**
     * 根据orderid获取order
     * @param orderId
     * @return
     */
    @GetMapping("/orders/{orderId}")
    public CommonResponse getOrderById(@PathVariable("orderId")int orderId){
        return orderService.getOrderByOrderId(orderId);
    }

    /**
     * 根据orderid获取lineitem
     * @param orderId
     * @return
     */
    @GetMapping("/lineItems/order/{orderId}")
    public CommonResponse getLineItemByOrderId(@PathVariable("orderId")int orderId){
        return lineItemService.getLineItemsByOrderId(orderId);
    }

    /**
     * 对某个item立即购买
     * @param itemId
     * @param number
     * @param token
     * @return
     */
    @PutMapping("/user/buyItem")
    public CommonResponse userBuyItemAtOnce(String itemId, int number, @RequestHeader("Authorization") String token) {
        String username = JWTUtil.getTokenInfo(token, "username");
        //  默认买一个
        CommonResponse commonResponse = orderService.userBuyItemAtOnce(username, itemId, number);
        if(commonResponse.isSuccess()){
            Order order = (Order) commonResponse.getData();
//            model.addAttribute("order", order);
//            model.addAttribute("tempOrderId", order.getOrderid());
//            CommonResponse commonResponse10 = lineItemService.getLineItemsByOrderId(order.orderid);
//            List<LineItem> lineItems = (List<LineItem>) commonResponse10.getData();
//            return "cartOrder/confirmOrder";
            Map<String, Object> map = new HashMap<>();
            map.put("orderId", order.getOrderid());
            return CommonResponse.creatForSuccess(map);
        }
        return commonResponse;

//        commonResponse = itemService.getItemByItemid(itemId);
//        Item item = (Item) commonResponse.getData();
//        model.addAttribute("errorMsg", commonResponse.getMessage());
//        CommonResponse commonResponse10 = productService.getProductByProductId(item.getProductid());
//        Product product = (Product) commonResponse10.getData();
////            System.out.println(product);
//        model.addAttribute("product", product);
//        CommonResponse commonResponse1 = itemService.getItemByItemid(itemId);
//        model.addAttribute("item", commonResponse1.getData());
////            System.out.println(commonResponse.getData());
////            到item详情页面
//        return "catalog/item";
    }

    /**
     * 从购物车付款
     * @param token
     * @return
     */
    @GetMapping("/user/newOrder")
    public CommonResponse userNewOrder(@RequestHeader("Authorization") String token){
        String username = JWTUtil.getTokenInfo(token, "username");
        CommonResponse commonResponse = orderService.userBuyCartItem(username);
        if(commonResponse.isSuccess()){
            Order order = (Order) commonResponse.getData();
            Map map = new HashMap<>();
            map.put("orderId", order.getOrderid());
            return CommonResponse.creatForSuccess(map);
        }
        return CommonResponse.creatForError(commonResponse.getMessage());
    }

    /**
     * 确认订单并去支付
     * @param order
     * @param orderId
     * @return
     */
    @PutMapping("/orders/{orderId}")
    public CommonResponse confirmAndPay(@RequestBody Order order, @PathVariable("orderId") String orderId) throws AlipayApiException {

        System.out.println("orderId" + orderId);
        System.out.println(order);
        CommonResponse commonResponse = orderService.updateOrderByOrderId(order);
        Order order1 = (Order) commonResponse.getData();
        commonResponse = ZFBqrUtil.getPayUrl(order1.getTotalprice());
        order1.setOutTradeNo((String) ((Map)commonResponse.getData()).get("outTradeNo"));
        order1.setQrcode((String) ((Map)commonResponse.getData()).get("qrcode"));
        orderService.updateOrderByOrderId(order1);
        return commonResponse;
    }

//  确认订单并去支付
//    @PostMapping("/pay")
//    public CommonResponse confirmAndPay(@RequestBody JSONObject requestBody, @RequestHeader("Authorization") String token){
//        String orderId = requestBody.getString("orderId");
//        Order order = new Order();
//        order.set
//        orderService.updateOrderByOrderId(order, orderId);
//    }

    /**
     * 获取qrcode和订单编号
     * @param orderId
     * @return
     * @throws AlipayApiException
     */
    @GetMapping("/qrCode/{orderId}")
    public CommonResponse getQrcode(@PathVariable("orderId") int orderId) throws AlipayApiException {
        Order order = (Order) orderService.getOrderByOrderId(orderId).getData();
        Map res = new HashMap<>();
        if(order.getOutTradeNo() == null || order.getOutTradeNo() == "" || order.getQrcode() == null || order.getQrcode() == ""){
            Map map = ZFBqrUtil.getQR(order.getTotalprice());
            String outTradeNo = (String) map.get("outTradeNo");
            orderService.updateOutTradeNoByOrderId(outTradeNo, orderId);
            String qrcode = (String) map.get("qrcode");
            orderService.updateQrcodeByOrderId(qrcode, orderId);
            return CommonResponse.creatForSuccess(map);
        }else{
            LocalDateTime localDate = order.getOrderDate();
            LocalDateTime localDateTime = LocalDateTime.now();

            Duration duration = Duration.between(localDateTime,  localDate );
            if(duration.toMinutes() > 60){
                return CommonResponse.creatForError("二维码已经失效");
            }
            res.put("outTradeNo", order.getOutTradeNo());
            res.put("qrcode", order.getQrcode());
            return CommonResponse.creatForSuccess(res);
        }
    }

    /**
     * 更新支付状态
     * @param outTradeNo
     * @return
     */
    @PostMapping("/orders/pay/{outTradeNo}")
    public CommonResponse setOrderPay(@PathVariable("outTradeNo") String outTradeNo){
        return orderService.updatePayByOutTradeNo(outTradeNo);
    }

    /**
     * 获取订单支付状态
     * @param orderId
     * @return
     * @throws Exception
     */
    @GetMapping("/payStatus/{orderId}")
    public CommonResponse finishPay(@PathVariable("orderId") int orderId)throws Exception{
        String outTradeNo = ((Order)orderService.getOrderByOrderId(orderId).getData()).getOutTradeNo();
        Object object = ZFBqrUtil.getPayStatue(outTradeNo);
        if(object == null || ((String)object).equals("0.00")){
            return CommonResponse.creatForError("您尚未付款!");
        }
//        将订单改成支付过的状态
        boolean result = orderService.finishPay(orderId);
        if(result){
            return CommonResponse.creatForSuccessMessage("支付成功");
        }else{
            return CommonResponse.creatForError("系统出错了!");
        }
    }

    /**
     * 用户要取消订单，返回操作结果
     * @param orderId
     * @return
     */
    @DeleteMapping("/cancelOrders/{orderId}")/*用户取消订单*/
    public CommonResponse userDeleteOrder(@PathVariable("orderId") int orderId){
        return orderService.userDeleteOrder(orderId);
    }

    /**
     * 用户退货，退整个订单的全部货物，返货操作结果
     * @param orderId
     * @return
     */
    @DeleteMapping("/returnOrders/{orderId}")
    public CommonResponse userReturnOrder(@PathVariable("orderId") int orderId){
        return orderService.userReturnOrder(orderId);
    }
}
